<script setup lang='ts'>
import type { IAddCoupons, IEditDetail } from '@fl/api/anjutong/model/coupons-model'
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridInstance, VxeGridListeners, VxeGridProps } from 'vxe-table'

import { Coupons, addCoupons, businessModules, couponsDetail, editDetail, treeType } from '@fl/api/anjutong'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import VoucherForm from './voucher-form.vue'

const formType = ref<'复制' | '新建' | '编辑'>('新建')
const TitleEnum = {
    add: '新建',
    copy: '复制',
    edit: '编辑',
} as const

type Item = {
    children?: Item[]
    code: string
    name: string
}

const centerDialogVisible = ref(false)
const router = useRouter()

const searchForm = ref({
    businessModule: '',
    couponName: '',
    couponType: '',
    isEnabled: '',
    projectName: '',
})
const formparams = ref({
    DateArr: [] as any[],
    businessModule: [] as any[],
    couponName: '',
    description: '',
    developer: '',
    discountAmount: 0,
    discountInstructions: '',
    expirationReminder: '1',
    expirationReminderNum: 0,
    id: '',
    isEnabled: 0,
    issueQuantity: 0,
    projectArr: [] as any[],
    projectSelect: '1',
    receiveInstructions: '',
    receiveLimit: '1',
    receiveLimitNum: 0,
    receivePopulation: '1',
    receivePopulationNum: 0,
    serviceProvider: '',
    thresholdAmount: '1',
    thresholdAmountNum: 0,
    usageLimit: '1',
    usageLimitNum: 0,
    usageNotes: '',
    validityDays: 0,
    validityPeriodType: '1',
})
const businessModuleList = ref([])
const projectList = ref([])

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        label: '业务板块',
        options: computed(() => {
            const arr = businessModuleList.value.map((item: any) => {
                return {
                    label: item.name,
                    value: item.code,
                }
            })
            return arr
        }),
        prop: 'businessModule',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '优惠类型',
        options: computed(() => {
            if (searchForm.value.businessModule) {
                const params: any = businessModuleList.value.find((item: any) => item.code === searchForm.value.businessModule)
                return params?.children?.map((item: any) => {
                    return {
                        label: item.name,
                        value: item.code,
                    }
                }) ?? []
            }
            return []
        }),
        prop: 'couponType',
        valueType: 'select',
    },

    {
        colProps: {
            span: 8,
        },
        label: '优惠券名称',
        prop: 'couponName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '状态',
        options: [
            {
                label: '启用',
                value: '1',
            },
            {
                label: '未启用',
                value: '0',
            },

        ],
        prop: 'isEnabled',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '项目名称',
        prop: 'projectName',
        valueType: 'copy',
    },

]
const businessModuleTitle = {
    1: '好房',
    2: '保障房',
    4: '房交会',
} as const
const statusBtnContent = {
    0: '启用',
    1: '停用',
} as const
const businessModuleType = computed(() => {
    const params: any = businessModuleList.value.find((item: any) => item.code === formparams.value.businessModule?.[0])
    return params?.name ?? ''
})
const dialogTitle = computed(() => {
    return `${formType.value}优惠券`
})
watch(() => searchForm.value.businessModule, () => {
    searchForm.value.couponType = ''
}, { deep: true })
watch(() => formparams.value.businessModule, (nval) => {
    if (nval?.[0]) {
        const option: any = {
            保障房: '2',
            好房: '1',
            房交会: '4',
        }
        treeType({ treeType: option[businessModuleType.value] }).then((res) => {
            projectList.value = res
        }).catch(() => {
            projectList.value = []
        })
    }
    else {
        formparams.value.projectSelect = ''
    }
}, { deep: true })
watch(() => formparams.value.projectSelect, (nval) => {
    console.log('🚀 ~ watch ~ nval:', nval)
    if (Number(nval) === 1)
        formparams.value.projectArr = []
}, { deep: true })

type RowVO = {
    businessModuleName: string
    couponName: string
    couponTypeName: string

}

const xGrid = ref<VxeGridInstance<RowVO>>()

const gridOptions = reactive<VxeGridProps<RowVO>>({
    align: 'center',
    border: true,
    columnConfig: {
        resizable: true,
    },
    columns: [
        { field: 'couponName', title: '优惠券名称', width: 200 },
        { field: 'businessModuleName', title: '业务板块' },
        { field: 'couponTypeName', title: '优惠类型' },
        { field: 'projectName', title: '项目名称', width: 150 },
        { field: 'issueQuantity', title: '发放数量' },
        { field: 'stock', title: '剩余库存' },
        { field: 'discountAmount', title: '优惠金额' },
        { slots: { default: 'status' }, title: '优惠券状态' },
        { slots: { default: 'interval' }, title: '有效期' },
        { slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
    data: [],
    editConfig: {
        mode: 'row',
        showStatus: true,
        trigger: 'manual',
    },
    height: 530,
    keepSource: true,
    loading: false,
    pagerConfig: {
        currentPage: 1,
        enabled: true,
        pageSize: 10,
        pageSizes: [10, 20, 50, 100, 200, 500],
        total: 0,
    },
    showOverflow: true,
})

async function findList() {
    gridOptions.loading = true
    try {
        const option = {
            businessModule: searchForm.value.businessModule,
            couponName: searchForm.value.couponName,
            couponType: searchForm.value.couponType,
            isEnabled: searchForm.value.isEnabled,
            page: gridOptions.pagerConfig?.currentPage,
            projectName: searchForm.value.projectName,
            size: gridOptions.pagerConfig?.pageSize,
            sort: 'createTime,desc',
        }
        const data = await Coupons(option)
        gridOptions.loading = false
        if (gridOptions.pagerConfig)
            gridOptions.pagerConfig.total = data?.total ?? 0
        gridOptions.data = data?.records ?? []
    }
    catch (error) {
        gridOptions.loading = false
        gridOptions.data = []
    }
}

const gridEvents: VxeGridListeners<RowVO> = {
    pageChange({ currentPage, pageSize }) {
        if (gridOptions.pagerConfig) {
            gridOptions.pagerConfig.currentPage = currentPage
            gridOptions.pagerConfig.pageSize = pageSize
        }
        findList()
    },
}
function showDetail(row: any) {
    router.push({
        path: `/marketing-promotion/marketing/marketing-list/${row?.id}`,
    })
}
function reset() {
    searchForm.value = {
        businessModule: '',
        couponName: '',
        couponType: '',
        isEnabled: '',
        projectName: '',
    }
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.currentPage = 1
    findList()
}
findList()
async function getbusinessModules() {
    gridOptions.loading = true
    try {
        const data = await businessModules()
        businessModuleList.value = data
        console.log('🚀 ~ getbusinessModules ~ businessModuleList:', businessModuleList)
    }
    catch (error) {
        gridOptions.loading = false
    }
}
getbusinessModules()
function formatInterval(row: any) {
    if (row.effectiveDate && row.expirationDate)
        return `${row.effectiveDate.substring(0, 10)} 至 ${row.expirationDate.substring(0, 10)}`

    return ''
}
function deactivate(row: any) {
    try {
        const option = {
            businessModule: row?.businessModule,
            couponName: row?.couponName,
            couponType: row?.couponType,
            description: row?.description,
            developer: row?.developer,
            discountAmount: row?.discountAmount,
            discountInstructions: row?.discountInstructions,
            effectiveDate: row?.effectiveDate,
            expirationDate: row?.expirationDate,
            expirationReminder: row?.expirationReminder,
            id: row?.id,
            isEnabled: row?.isEnabled === 1 ? 0 : 1,
            issueQuantity: row?.issueQuantity,
            project: row?.project,
            projectName: row?.projectName,
            receiveInstructions: row?.receiveInstructions,
            receiveLimit: row?.receiveLimit,
            receivePopulation: row?.receivePopulation,
            serviceProvider: row?.serviceProvider,
            thresholdAmount: row?.thresholdAmount,
            usageLimit: row?.usageLimit,
            usageNotes: row?.usageNotes ?? 0,
            validityDays: row?.validityDays ?? 0,
            validityPeriodType: row?.validityPeriodType,
        }
        editCoupons(option)
    }
    catch (error) {

    }
}
async function editCoupons(option: IEditDetail) {
    try {
        const result = await editDetail(option)
        submitLoading.value = false
        if (result) {
            ElMessage.success('操作成功')
            centerDialogVisible.value = false
            findList()
        }
    }
    catch (error: any) {
        throw new Error(error || '')
    }
}
async function showForm(Title: '复制' | '新建' | '编辑', row?: any) {
    try {
        formType.value = Title
        if (formType.value === TitleEnum.copy || formType.value === TitleEnum.edit)
            await copyFrom(row)
        centerDialogVisible.value = true
    }
    catch (error) {
        console.log('🚀 ~ showForm ~ error:', error)
    }
}
const submitLoading = ref(false)
function formSubmit() {
    const options: IAddCoupons = {
        businessModule: formparams.value.businessModule?.[0] ?? '',
        couponName: formparams.value.couponName ?? '',
        couponType: formparams.value.businessModule?.[1] ?? '',
        description: formparams.value.description,
        developer: formatDeveloper(),
        discountAmount: formparams.value.discountAmount,
        discountInstructions: formparams.value.discountInstructions,
        effectiveDate: formparams.value.validityPeriodType === '1' ? formparams.value.DateArr?.[0] ?? '' : '',
        expirationDate: formparams.value.validityPeriodType === '1' ? formparams.value.DateArr?.[1] ?? '' : '',
        expirationReminder: formparams.value.expirationReminder === '1' ? -1 : formparams.value.expirationReminderNum ?? 0,
        isEnabled: formparams.value.isEnabled,
        issueQuantity: formparams.value.issueQuantity,
        project: formatFormProject(),
        projectName: formatProjectName(),
        receiveInstructions: formparams.value.receiveInstructions,
        receiveLimit: formparams.value.receiveLimit === '1' ? -1 : formparams.value.receiveLimitNum ?? 0,
        receivePopulation: formparams.value.receivePopulation === '1' ? -1 : formparams.value.receivePopulationNum ?? 0,
        serviceProvider: formatServiceProvider(),
        thresholdAmount: formparams.value.thresholdAmount === '1' ? -1 : formparams.value.thresholdAmountNum ?? 0,
        usageLimit: formparams.value.usageLimit === '1' ? -1 : formparams.value.usageLimitNum ?? 0,
        usageNotes: formparams.value.usageNotes,
        validityDays: formparams.value.validityPeriodType === '2' ? formparams.value.validityDays : 0,
        validityPeriodType: Number(formparams.value.validityPeriodType),
    }
    if (formType.value === TitleEnum.add || formType.value === TitleEnum.copy)
        return submitAddCoupons(options)

    if (formType.value === TitleEnum.edit)
        return editCoupons({ id: formparams.value.id, ...options })
    return ''
}

function formatProject(arr: any[]) {
    const result: any[] = []
    for (let i = 0; i < arr[0]?.length; i++) {
        const temp = new Set(arr.map(item => item[i]))
        result.push([...temp].join(','))
    }
    return result
}
function formatAllProject(arr: any[]) {
    const result: any[] = []
    const codes = arr.map(item => item.code).join(',')
    const childrenCodes = arr
        .map(item => item.children.map((child: any) => child.code).join(','))
        .join(',')
    result.push(codes, childrenCodes)

    return result
}

function formatDeveloper() {
    console.log(businessModuleType.value)
    if (formparams.value.projectSelect === '1' && (businessModuleType.value === businessModuleTitle[1] || businessModuleType.value === businessModuleTitle[4]))
        return formatAllProject(projectList.value)?.[0] ?? ''

    if (businessModuleType.value === businessModuleTitle[1] || businessModuleType.value === businessModuleTitle[4])
        return formatProject(formparams.value.projectArr)?.[0] ?? ''

    return ''
}

function formatServiceProvider() {
    if (formparams.value.projectSelect === '1' && businessModuleType.value === businessModuleTitle[2])
        return formatAllProject(projectList.value)?.[0] ?? ''

    if (businessModuleType.value === businessModuleTitle[2])
        return formatProject(formparams.value.projectArr)?.[0] ?? ''

    return ''
}
function formatFormProject() {
    if (formparams.value.projectSelect === '1')
        return formatAllProject(projectList.value)?.[1] ?? ''

    return formatProject(formparams.value.projectArr)?.[1] ?? ''
}
function formatProjectName() {
    const project = formatFormProject()?.split(',') ?? []
    const result = projectList.value
        .reduce((acc: string[], curr: Item) => {
            if (curr?.children) {
                const filteredChildren = curr?.children?.filter(child =>
                    project.includes(child?.code),
                )
                acc.push(...filteredChildren.map(child => child.name))
            }
            return acc
        }, [])
        .join(',')
    return result
}
async function submitAddCoupons(options: IAddCoupons) {
    submitLoading.value = true
    try {
        const result = await addCoupons(options)
        submitLoading.value = false
        if (result) {
            ElMessage.success('操作成功')
            centerDialogVisible.value = false
            findList()
        }
    }
    catch (error) {
        submitLoading.value = false
    }
}
function resetFormParams() {
    formparams.value = {
        DateArr: [] as any,
        businessModule: [] as any,
        couponName: '',
        description: '',
        developer: '',
        discountAmount: 0,
        discountInstructions: '',
        expirationReminder: '1',
        expirationReminderNum: 0,
        id: '',
        isEnabled: 0,
        issueQuantity: 0,
        projectArr: [] as any,
        projectSelect: '',
        receiveInstructions: '',
        receiveLimit: '1',
        receiveLimitNum: 0,
        receivePopulation: '1',
        receivePopulationNum: 0,
        serviceProvider: '',
        thresholdAmount: '1',
        thresholdAmountNum: 0,
        usageLimit: '1',
        usageLimitNum: 0,
        usageNotes: '',
        validityDays: 0,
        validityPeriodType: '1',
    }
}

async function copyFrom(row: any) {
    try {
        const data = await couponsDetail(row?.id)
        console.log('🚀 ~ copyFrom ~ data:', filterSelect(data?.projectTree))
        formparams.value = {
            DateArr: [data?.effectiveDate, data?.expirationDate],
            businessModule: [data?.businessModule, data?.couponType],
            couponName: data?.couponName,
            description: data?.description,
            developer: data?.developer,
            discountAmount: data?.discountAmount,
            discountInstructions: data?.discountInstructions,
            expirationReminder: data?.expirationReminder === -1 ? '1' : '2',
            expirationReminderNum: data?.expirationReminder === -1 ? 0 : data?.expirationReminder,
            id: data?.id,
            isEnabled: 0,
            issueQuantity: data?.issueQuantity,
            projectArr: reverseFormProject(data?.projectTree) === '1' ? [] : filterSelect(data?.projectTree),
            projectSelect: reverseFormProject(data?.projectTree),
            receiveInstructions: data?.receiveInstructions,
            receiveLimit: data?.receiveLimit === -1 ? '1' : '2',
            receiveLimitNum: data?.receiveLimit === -1 ? 0 : data?.receiveLimit,
            receivePopulation: data?.receivePopulation === -1 ? '1' : '2',
            receivePopulationNum: data?.receivePopulation === -1 ? 0 : data?.receivePopulation,
            serviceProvider: data?.serviceProvider,
            thresholdAmount: data?.thresholdAmount === -1 ? '1' : '2',
            thresholdAmountNum: data?.thresholdAmount === -1 ? 0 : data?.thresholdAmount,
            usageLimit: data?.usageLimit === -1 ? '1' : '2',
            usageLimitNum: data?.usageLimit === -1 ? 0 : data?.usageLimit,
            usageNotes: data?.usageNotes,
            validityDays: data?.validityDays,
            validityPeriodType: String(data?.validityPeriodType),
        }
        console.log(formparams, 'formparams')
    }
    catch (error: any) {
        throw new Error(error || '')
    }
}

function reverseFormProject(arr: any[]) {
    for (const item of arr) {
        for (const child of item.children) {
            if (!child.selected)
                return '2'
        }
    }
    return '1'
}
function filterSelect(arr: any[]) {
    const result: any[] = []
    for (const item of arr) {
        for (const child of item.children) {
            if (child.selected)
                result.push([item.code, child.code])
        }
    }
    return result
}
function search() {
    if (gridOptions.pagerConfig)
        gridOptions.pagerConfig.currentPage = 1
    findList()
}
function updateproject(val: any) {
    formparams.value.projectArr = val
}
</script>

<template>
    <div class="mb-30 bg-white px-20 py-10">
        <PlusForm v-model="searchForm"
                  :row-props="{ gutter: 20 }"
                  :columns="columns"
                  label-width="100"
        >
            <template #footer>
                <div class="ml-auto">
                    <el-button type="primary"
                               @click="search"
                    >
                        查询
                    </el-button>

                    <el-button @click="reset">
                        重置
                    </el-button>
                </div>
            </template>
        </PlusForm>
    </div>

    <div class="bg-white p-20">
        <div class="fw-700">
            优惠券列表
        </div>

        <div class="my-10 flex justify-end">
            <el-button type="primary"
                       @click="showForm(TitleEnum.add)"
            >
                {{ TitleEnum.add }}
            </el-button>
        </div>

        <vxe-grid ref="xGrid"
                  v-bind="gridOptions"
                  v-on="gridEvents"
        >
            <template #interval="{ row }">
                {{ formatInterval(row) }}
            </template>

            <template #status="{ row }">
                {{ row?.isEnabled === 1 ? '启用' : '未启用' }}
            </template>

            <template #operate="{ row }">
                <vxe-button :content="TitleEnum.edit"
                            @click="showForm(TitleEnum.edit, row)"
                />

                <vxe-button content="数据"
                            @click="showDetail(row)"
                />

                <vxe-button :content="TitleEnum.copy"
                            @click="showForm(TitleEnum.copy, row)"
                />

                <vxe-button :content="statusBtnContent[(row?.isEnabled as 0 | 1)]"
                            @click="deactivate(row)"
                />
            </template>
        </vxe-grid>
    </div>

    <el-dialog v-model="centerDialogVisible"
               :title="dialogTitle"
               width="800"
               destroy-on-close
               align-center
               :close-on-click-modal="false"
               @close="resetFormParams"
    >
        <div class="max-h-500 of-auto pb-10">
            <VoucherForm :formparams="formparams"
                         :businessmodulelist="businessModuleList"
                         :project-list="projectList"
                         :submit-loading="submitLoading"
                         :type="formType"
                         @close=" centerDialogVisible = false"
                         @submit="formSubmit"
                         @updateproject="updateproject"
            />
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>

</style>
